package connection;

import connection.authorization.AuthorizationData;
import connection.commands.GetFileCommand;
import connection.commands.GetFilesCommand;
import connection.commands.GetLastVersionCommand;
import connection.commands.PutFileCommand;
import connection.replies.*;
import connection.request.Request;
import interfaces.clients.dispatcher.replies.BaseReply;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.List;

/**
 * A class, which can execute interfaces.clients.dispatcher.replies.replies on the server.<br>
 * <br>
 *
 * @author Mihail A. Muhin
 */
public class ConnectionSystem implements Connection {
  //IP of the server, to which this module will try to connect
  //TODO: remove this
  private static final String connection_ip = "127.0.0.1";

  //port number on the server, to which this module will try to connect
  //TODO: remove this
  private static final int connection_port = 5000;

  private Socket ss = null;
  private ObjectInputStream ois = null;
  private ObjectOutputStream oos = null;

  private BaseReply execute(Request r) {
    BaseReply res = null;
    try {
      ss = new Socket(connection_ip, connection_port);

      oos = new ObjectOutputStream(ss.getOutputStream());
      r.write(oos);
      oos.flush();
      ss.shutdownOutput();

      ois = new ObjectInputStream(ss.getInputStream());
      res = RepliesReader.read(ois);
      ss.shutdownInput();

      ss.close();
      ss = null;
      oos = null;
      ois = null;
    } catch (Throwable e) {
      e.printStackTrace();
    }
    return res;
  }

  public ConnectionSystem() {

  }

  public String getFile(String filename, int version) {
    AuthorizationData adata = new AuthorizationData("", "");
    GetFileCommand cdata = new GetFileCommand(filename, version);
    Request r = new Request(adata, cdata);

    GetFileReply res = (GetFileReply) execute(r);
    return res.getContents();
  }

  public void putFile(String filename, String contents) {
    AuthorizationData adata = new AuthorizationData("", "");
    PutFileCommand cdata = new PutFileCommand(filename, contents);
    Request r = new Request(adata, cdata);

    PutFileReply res = (PutFileReply) execute(r);
  }

  public int getLastVersion(String filename) {
    AuthorizationData adata = new AuthorizationData("", "");
    GetLastVersionCommand cdata = new GetLastVersionCommand(filename);
    Request r = new Request(adata, cdata);

    GetLastVersionReply res = (GetLastVersionReply) execute(r);
    return res.getNum();
  }

  public List getFiles() {
    AuthorizationData adata = new AuthorizationData("", "");
    GetFilesCommand cdata = new GetFilesCommand();
    Request r = new Request(adata, cdata);

    GetFilesReply res = (GetFilesReply) execute(r);
    return res.getList();
  }
}
